package com.wsc.metastock;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.wsc.metastock.constants.YahooConstants;
import com.wsc.metastock.exception.InvalidSplitCountException;
import com.wsc.metastock.model.bean.Config;
import com.wsc.metastock.model.bean.Quote;
import com.wsc.metastock.util.Command;
import com.wsc.metastock.util.DateUtil;

public class UpdateQuotes implements YahooConstants {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");
        Config config = (Config) applicationContext.getBean("config");
        for (String symbol : config.getAllSymbols()) {
            ArrayList<Quote> quotes = new ArrayList<Quote>();
            quotes.add(today(symbol));
            quotes.addAll(historical(symbol, config.getStartDate()));
            Collections.sort(quotes, Collections.reverseOrder());
            try {
                config.checkSplit(quotes);
            } catch (InvalidSplitCountException e) {
                e.printStackTrace();
            }
            saveASCFile(quotes);
            execute();
        }
    }

    private static void saveASCFile(ArrayList<Quote> quotes) {
        BufferedWriter out;
        try {
            out = new BufferedWriter(new FileWriter("quotes.asc"));
            for (Quote quote : quotes) {
                out.write(quote.toString() + "\n");
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void execute() {
        Command asc2ms = new Command(new String[] { "cmd.exe", "/c", "asc2ms -f quotes.asc -r r -o masterdir" });
        asc2ms.start();

        do {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (asc2ms.isAlive());

        //delete the asc file
        Command delASCFile = new Command(new String[] { "cmd.exe", "/c", "del /s quotes.asc /q" });
        delASCFile.start();

    }

    private static Quote today(String stock) {
        URL yahoo;
        URLConnection yahooConnection;
        Quote quote = new Quote();
        BufferedReader in;
        try {
            yahoo = new URL(URL_QUOTES + stock + "&f=" + SYMBOL + OPEN + DAY_HIGH + DAY_LOW + LAST_TRADE_PRICE_ONLY + VOLUME);
            yahooConnection = yahoo.openConnection();
            in = new BufferedReader(new InputStreamReader(yahooConnection.getInputStream()));
            String inputLine;
            if ((inputLine = in.readLine()) != null) {
                String symbol = inputLine.split(",")[0];
                symbol = symbol.substring(1, symbol.length() - 4);
                quote.setSymbol(symbol);
                String open = inputLine.split(",")[1];
                quote.setOpen(open);
                String dayHigh = inputLine.split(",")[2];
                quote.setHigh(dayHigh);
                String dayLow = inputLine.split(",")[3];
                quote.setLow(dayLow);
                String last_trade = inputLine.split(",")[4];
                quote.setClose(last_trade);
                String volume = inputLine.split(",")[5];
                quote.setVolume(volume);
                quote.setDate(DateUtil.now(DATE_FORMAT));
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return quote;
    }

    private static ArrayList<Quote> historical(String symbol, String startDateUserDefined) {
        Calendar startDate = DateUtil.getCalendarDate(DATE_FORMAT, startDateUserDefined);
        Calendar endDate = DateUtil.getCalendarDate(DATE_FORMAT, DateUtil.now(DATE_FORMAT));
        ArrayList<Quote> quotes = new ArrayList<Quote>();
        Quote quote;

        URL yahoo;
        try {
            yahoo = new URL(URL_HISTORICAL + symbol + "&a=" + startDate.get(Calendar.MONTH) + "&b="
                    + startDate.get(Calendar.DAY_OF_MONTH) + "&c=" + startDate.get(Calendar.YEAR) + "&d="
                    + (endDate.get(Calendar.MONTH)) + "&e=" + endDate.get(Calendar.DAY_OF_MONTH) + "&f="
                    + endDate.get(Calendar.YEAR) + "&g=d&ignore=.csv");
            URLConnection yahooConnection = yahoo.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yahooConnection.getInputStream()));
            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                quote = new Quote();
                quote.setSymbol(symbol.substring(0, symbol.length() - 3));
                quote.setDate(inputLine.split(",")[0].replace("-", ""));
                String open = inputLine.split(",")[1];
                quote.setOpen(open);
                String dayHigh = inputLine.split(",")[2];
                quote.setHigh(dayHigh);
                String dayLow = inputLine.split(",")[3];
                quote.setLow(dayLow);
                String close = inputLine.split(",")[4];
                quote.setClose(close);
                String volume = inputLine.split(",")[5];
                if (new Double(volume).doubleValue() > 0) {
                    quote.setVolume(volume);
                    quotes.add(quote);
                }
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return quotes;
    }

}
